import { Outlet, useLocation } from 'react-router-dom'
import Navigation from './Navigation' //导航栏和侧边栏的组件
import BottomNavigation from './BottomNavigation' // 底部导航组件
import { useState, useEffect, useRef } from 'react'
import useIsMobile from '@/hooks/isMoboile'
import Footer from './Footer'
import { useAuth } from '@/hooks/useAuth'
import { useGoogleLoginCallback } from '@/hooks/useGoogleLoginCallback'
import ToastNotification from './ToastNotification'
import { messageApi } from '@/hooks/messageApi'
import { matchPath } from 'react-router-dom'


// 主布局组件，包含导航和内容区，使用 Tailwind CSS
export default function Layout() {
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false)// 控制侧边栏展开/收起的状态
  const [sidebarVisible, setSidebarVisible] = useState(false)// 移动端侧边栏显示/隐藏
  const isMobile = useIsMobile() //判断是否是移动端
  const [headerHidden, setHeaderHidden] = useState(false)// header隐藏状态
  const lastScroll = useRef(0) //监听滚动条事件
  const getInitialTab = () => {
    const lastType = localStorage.getItem('last_chat_type');
    // 合法值 girl, man, anime_girl, anime_man
    if (lastType === 'girl' || lastType === 'man' || lastType === 'anime_girl' || lastType === 'anime_man') {
      return lastType;
    }
    return 'anime_girl'; // 未登录时默认 anime_girl
  };// 读取localStorage的last_chat_type，决定初始tab
  const [activeTab, setActiveTab] = useState(getInitialTab())
  const location = useLocation()
  const { userData } = useAuth()
  const { show: showToastState, message: toastMessage, type: toastType, showToast } = messageApi()

  // 处理谷歌登录回调
  useGoogleLoginCallback()

  // 需要隐藏 Footer 和 BottomNavigation 的路径规则
  const hideFooterAndNavRoutes = [
    '/conversation',
  ];

  // 需要隐藏 Footer 的路径规则（包含更多页面）
  const hideFooterRoutes = [
    '/conversation',
    '/ai-companion/:id/album',
    '/forget-password',
    '/setPassWord',
    '/subscriptions',
    '/collections',
    '/collection',
    '/PayMoney',
    '/settings',
    '/buygems'
  ];

  // 判断当前路径是否需要隐藏 Footer 和 BottomNavigation
  const shouldHideFooterAndNav = hideFooterAndNavRoutes.some(pattern =>
    matchPath({ path: pattern, end: true }, location.pathname)
  );

  // 判断当前路径是否需要隐藏 Footer
  const shouldHideFooter = hideFooterRoutes.some(pattern =>
    matchPath({ path: pattern, end: true }, location.pathname)
  );

  // 判断是否为Chat页面
  const isChatPage = matchPath({ path: '/conversation', end: true }, location.pathname);

  // 判断是否为Subscriptions页面
  const isSubscriptionsPage = matchPath({ path: '/subscriptions', end: true }, location.pathname);

  // 判断是否为ForgetPassword页面
  const isForgetPasswordPage = matchPath({ path: '/forget-password', end: true }, location.pathname);

  // 判断是否为SetPassWord页面
  const isSetPassWordPage = matchPath({ path: '/setPassWord', end: true }, location.pathname);

  // 判断是否为CreatAi页面
  const isCreatAiPage = matchPath({ path: '/create-character', end: true }, location.pathname);

  // 判断是否为GenerateImage页面
  const isGenerateImagePage = matchPath({ path: '/collections', end: true }, location.pathname);

  // 判断是否为 Collection 页面
  const isCollection = matchPath({ path: '/collection', end: true }, location.pathname);

  // 判断是否为PayMoney页面
  const isPayMoneyPage = matchPath({ path: '/PayMoney', end: true }, location.pathname);

  // 判断是否为Settings页面
  const isSettingsPage = matchPath({ path: '/settings', end: true }, location.pathname);

  // 判断是否为BuyToken页面
  const isBuyTokenPage = matchPath({ path: '/buygems', end: true }, location.pathname);

  // 切换侧边栏展开/收起状态的函数
  const toggleSidebar = () => {
    if (isMobile) {
      setSidebarVisible(v => !v)
    } else {
      setSidebarCollapsed(v => !v)
    }
  }

  // 监听滚动，控制header隐藏/显示
  useEffect(() => {
    if (!isMobile) {
      setHeaderHidden(false)
      return;
    }
    // 滚动条事件 触发header的显示与隐藏
    const handleScroll = () => {
      const st = window.scrollY
      if (st > lastScroll.current && st > 32) {
        setHeaderHidden(true)
      } else {
        setHeaderHidden(false)
      }
      lastScroll.current = st
    }
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [isMobile])

  // 在移动端阻止下层的滚动点击事件 
  useEffect(() => {
    if (sidebarVisible && isMobile) {
      const originalOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = originalOverflow;
      };
    }
  }, [sidebarVisible, isMobile]);

  // 监听用户数据变化，更新 activeTab
  useEffect(() => {
    if (userData?.last_chat_type && ['girl', 'man', 'anime_girl', 'anime_man'].includes(userData.last_chat_type)) {
      setActiveTab(userData.last_chat_type);
    }
  }, [userData]);

  return (
    <div
      // className="flex flex-col min-h-screen"
      className="flex flex-col"
    >
      {/* Toast 提示弹窗 */}
      <ToastNotification
        show={showToastState}
        message={toastMessage}
        type={toastType}
      />
      {/* 导航组件 - 在移动端Chat页面时不显示 */}
      {!(isMobile && isChatPage) && (
        <Navigation
          isMobile={isMobile}
          sidebarCollapsed={sidebarCollapsed}
          sidebarVisible={sidebarVisible}
          toggleSidebar={toggleSidebar}
          headerHidden={headerHidden}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
        />
      )}

      {/* 内容区域容器 - 根据是否显示Navigation调整样式 */}
      <div
        className={`flex ${!(isMobile && isChatPage) ? 'mt-[4em]' : ''}`}
      // style={{ minWidth: !isMobile ? '1240px' : undefined }}
      >
        {/* 侧边栏占位 - 只在PC端且显示Navigation时显示 */}
        {!isMobile && (
          <div
            style={{
              width: sidebarCollapsed ? '4.5rem' : '14rem', // 和 DesktopSidebar 的 w-18(4.5rem) 和 w-56(14rem) 保持一致
              transition: 'width 0.3s'
            }}
          />
        )}

        {/* 内容区域 外层盒子 */}
        <div className="flex-1 bg-[rgb(19,19,19)]">
          {/* 内容区域内层 px-3 py-4 sm:px-6 sm:py-6 md:px-8 md:py-8 lg:px-12 lg:py-10 xl:px-8 xl:py-6 2xl:px-24 2xl:py-8 */}
          <div
            className={`${!isChatPage && !isSubscriptionsPage && !isForgetPasswordPage && !isSetPassWordPage && !isGenerateImagePage && !isCollection && !isPayMoneyPage && !isSettingsPage && !isBuyTokenPage ? '' : ''}`}
            style={{
              paddingBottom: isMobile && !shouldHideFooterAndNav ? '5rem' : undefined, // 为底部导航栏留出空间
            }}
          >
            <Outlet context={{ activeTab, setActiveTab }} />
          </div>

          {/* Footer - 只在不需要隐藏时渲染 */}
          {!shouldHideFooter && !isCreatAiPage && (
            <div
              className="w-full"
              style={{
                marginBottom: isMobile ? '5rem' : '0' // 为底部导航栏留出额外空间
              }}
            >
              <Footer />
            </div>
          )}
        </div>
      </div>

      {/* 底部导航组件 - 只在移动端子路由中且不需要隐藏时显示 */}
      {!shouldHideFooterAndNav && (
        <BottomNavigation
          isMobile={isMobile}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
        />
      )}
    </div>
  )
} 